package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"strings"
	"time"
)

type Ssrc struct {
	Ssrc     uint32 `orm:"pk"`
	KernelId string
	Expair   time.Time
	Create   time.Time `orm:"auto_now;type(datetime)"`
	Invalid  int32
}

func GetKernelIdBySsrc(ssrc uint32) (*Ssrc, error) {
	newSsrc := Ssrc{
		Ssrc: ssrc,
	}

	o := orm.NewOrm()
	o.Using("default")

	err := o.Read(&newSsrc)
	return &newSsrc, err
}

func RegSSRC() {
	orm.RegisterModel(new(Ssrc))
}

func Init(user, pwd, serv string) error {

	orm.Debug = true
	orm.RegisterDriver("mysql", orm.DRMySQL)
	maxIdle := 30
	maxConn := 30

	mysqlAuth := fmt.Sprintf("%s:%s@tcp(%s)/webank_ivr?charset=utf8&loc=Local", user, pwd, serv)

	return orm.RegisterDataBase("default", "mysql", mysqlAuth, maxIdle, maxConn)

	//orm.RegisterModel(new(Ssrc))

}

type IpccLostNumberFind struct {
	Id         int
	Md5        string
	RealNumber string
	Describ    string    `orm:"null"`
	UpdateTime time.Time `orm:"null"`
}

func GetNumberByMd5(md5 string) (string, error) {

	number := IpccLostNumberFind{
		Md5: strings.ToUpper(md5),
	}

	o := orm.NewOrm()
	o.Using("default")

	err := o.QueryTable("IpccLostNumberFind").Filter("Md5", number.Md5).One(&number)

	return number.RealNumber, err
}

func RegLostAndFind() {
	orm.RegisterModel(new(IpccLostNumberFind))
}
